import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/record/recent_channel_entity.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/widgets/base/wqs_button.dart';
import 'package:ball_lion/widgets/base/wqs_image.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/widgets/loading/no_data_widget.dart';
import 'package:visibility_detector/visibility_detector.dart';
import 'package:ball_lion/entity/my/team_focus_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/server/api/user_api.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/ladder_tab_bar.dart';

class ChannelFocusPage extends StatefulWidget {
  const ChannelFocusPage({super.key, this.sportsId = 1});

  final int sportsId;

  @override
  State<ChannelFocusPage> createState() => _ChannelFocusPageState();
}

class _ChannelFocusPageState extends State<ChannelFocusPage>
    with AutomaticKeepAliveClientMixin {
  int _index = 0;
  int get sportsId => widget.sportsId;
  List<TeamFocusEntity>? _teams;
  List<RecentChannelEntity>? _channels;
  bool _edit = false;

  int get index => _index;
  bool get edit => _edit;
  List<RecentChannelEntity>? get channels => _channels;
  List<TeamFocusEntity>? get teams => _teams;

  set teams(List<TeamFocusEntity>? value) => setState(() => _teams = value);
  set channels(List<RecentChannelEntity>? value) =>
      setState(() => _channels = value);
  set edit(bool value) => setState(() => _edit = value);
  set index(int value) => setState(() => _index = value);

  Future getFocus() async {
    if (channels == null || index == 0) {
      channels = await UserApi.getChannelFocusList(sportsId: sportsId);
    }
    if (teams == null || index == 1) {
      teams = await UserApi.getTeamFocusList(sportsId: sportsId);
    }
  }

  @override
  void initState() {
    if (User.isLogin) getFocus();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return VisibilityDetector(
      key: const Key("channel_focus"),
      onVisibilityChanged: (VisibilityInfo info) {
        if (!info.visibleBounds.isEmpty && User.isLogin) {
          getFocus();
        }
      },
      child: Scaffold(
          body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: Get.width,
            color: Colours.greyF2F3F7,
            padding: const EdgeInsets.only(top: 10),
            child: Row(
              children: [
                Expanded(
                  child: LadderTabBar(
                    key: Key("$sportsId"),
                    tag: "$sportsId",
                    tabs: ["赛事", "球队"].map((e) => QsText(e)).toList(),
                    selectLabelStyle: TabStyle(color: Colours.text),
                    labelStyle: TabStyle(
                        color: Colours.grey99, weight: FontWeight.w600),
                    needEnd: false,
                    scrollable: true,
                    keepSize: true,
                    initialIndex: index,
                    labelPadding: const EdgeInsets.symmetric(horizontal: 4),
                    onTap: (value) => index = value,
                  ),
                ),
                if (!edit) ...[
                  Image.asset(Utils.getImgPath("rank_focus.png"),
                          width: 20, color: Colours.grey99)
                      .paddingOnly(right: 17)
                      .tap(() async {
                    edit = true;
                  })
                ] else ...[
                  const QsText("按住拖动条调整顺序",
                      fontSize: 12, color: Colours.grey99),
                  Container(width: 6),
                  Image.asset(Utils.getImgPath("edit_check.png"), width: 20)
                      .paddingOnly(right: 16)
                      .tap(() async {
                    edit = false;
                    int? result;
                    if (index == 0) {
                      result = await UserApi.updateFocusChannel(
                          channels?.map((e) => e.id ?? 0).toList(), sportsId);
                    } else if (index == 1) {
                      result = await UserApi.updateFocusTeam(
                          teams?.map((e) => e.id ?? 0).toList(), sportsId);
                    }
                    if (result == 200) {
                      Toast.text("更改成功");
                      getFocus();
                    } else {
                      Toast.text("更改失败");
                    }
                  })
                ]
              ],
            ),
          ),
          Expanded(child: contentList(index))
        ],
      )),
    );
  }

  Widget contentList(int index) {
    return LoadingWidget<bool>(
      isLoading: false,
      data: !User.isLogin,
      noData: NoDataWidget(
          tip: "登录后才能关注比赛",
          buttonText: "去登录",
          onTap: () => User.needLogin(() async {})),
      child: () => LoadingWidget<bool>(
        isLoading: index == 0 ? channels == null : teams == null,
        data: index == 0 ? channels?.length == 0 : teams?.length == 0,
        noData: NoDataWidget(tip: "暂无关注${index == 0 ? "赛事" : "球队"}"),
        child: () => ReorderableListView.builder(
          buildDefaultDragHandles: false,
          proxyDecorator: (child, index, animation) =>
              proxyDecorator(child, index, animation),
          onReorder: (int oldIndex, int newIndex) {
            if (oldIndex < newIndex) {
              if (index == 0) {
                channels!.insert(newIndex, channels![oldIndex]);
                channels!.removeAt(oldIndex);
              } else {
                teams!.insert(newIndex, teams![oldIndex]);
                teams!.removeAt(oldIndex);
              }
            } else if (oldIndex > newIndex) {
              if (index == 0) {
                channels!.insert(newIndex, channels![oldIndex]);
                channels!.removeAt(oldIndex + 1);
              } else {
                teams!.insert(newIndex, teams![oldIndex]);
                teams!.removeAt(oldIndex + 1);
              }
            }
          },
          itemCount: (index == 0 ? channels?.length : teams?.length) ?? 0,
          itemBuilder: (BuildContext context, int i) {
            return tile(index == 0 ? (channels?[i].logo) : teams?[i].logo,
                index == 0 ? (channels?[i].name) : teams?[i].nameChsShort, i);
          },
        ),
      ),
    );
  }

  Widget tile(String? logo, String? name, int order) {
    double size = 24;
    return ListTile(
        key: ValueKey(order),
        onTap: () {
          if (index == 0) {
            Get.toNamed(Routes.leagueDetail,
                arguments: channels?[order].id,
                parameters: {"type": "${sportsId - 1}"});
          } else if (index == 1) {
            Get.toNamed(
                sportsId == 1 ? Routes.zqTeamDetail : Routes.lqTeamDetail,
                arguments: teams?[order].id);
          }
        },
        contentPadding: EdgeInsets.only(
            left: 16,
            bottom: order ==
                    ((index == 0 ? channels?.length : teams?.length) ?? 0) - 1
                ? 70
                : 0),
        leading: ClipRRect(
          borderRadius: BorderRadius.circular(2),
          child: QsImage(
            imageUrl: logo,
            width: size,
            height: size,
            placeholder: Styles.placeholderIcon(width: size, height: size),
            errorWidget: Image.asset(
                Utils.getImgPath("record_channel_icon.png"),
                width: size,
                height: size),
          ),
        ),
        title: QsText(name ?? "", fontSize: 13),
        trailing: ReorderableDragStartListener(
            enabled: edit,
            index: order,
            child: (!edit
                    ? QsButton(
                        onPressed: () => unFocus(order),
                        width: 57,
                        height: 24,
                        text: "已关注",
                        textStyle: const TextStyle(fontSize: 13),
                        foregroundColor: Colours.grey99,
                        backgroundColor: Colours.greyF2,
                        borderRadius: 4,
                      )
                    : Image.asset(Utils.getImgPath("drag_bar.png"), width: 20))
                .paddingOnly(right: 16)));
  }

  Widget proxyDecorator(Widget child, int index, Animation<double> animation) {
    return AnimatedBuilder(
      animation: animation,
      builder: (BuildContext context, Widget? child) {
        final double animValue = Curves.easeInOut.transform(animation.value);
        final double elevation = lerpDouble(0, 6, animValue)!;
        return Material(
          elevation: elevation,
          color: Colours.white,
          shadowColor: Colours.grey99.withOpacity(0.1),
          child: child,
        );
      },
      child: child,
    );
  }

  Future unFocus(int order) async {
    bool result = await WidgetUtils.alertQuery("确认取消关注吗？") ?? false;
    if (!result) return;
    if (index == 0) {
      int? result =
          await UserApi.unFocusChannel(channels?[order].id ?? 0, sportsId);
      if (result == 200) {
        Toast.text("取消关注成功");
        getFocus();
      } else {
        Toast.text("取消关注失败");
      }
    } else if (index == 1) {
      int? result = await UserApi.unFocusTeam(teams?[order].id ?? 0, sportsId);
      if (result == 200) {
        Toast.text("取消关注成功");
        getFocus();
      } else {
        Toast.text("取消关注失败");
      }
    }
  }

  @override
  bool get wantKeepAlive => true;
}
